package com.zrrd.learn.chapter08.ThreadWork;

/**
 * 灯
 *
 * @author asus
 * @version 1.0
 * @date 2023/8/2 13:58
 */
//请编写一个类，模拟灯被打开以及关闭两个功能，请尝试通过线程来完成。

public class Lamp extends Thread{

    //共享变量   灯状态

    private static boolean lightState = false;

    private synchronized void open() {
        if (!lightState) {
            lightState = true;
            System.out.println(Thread.currentThread().getName() + "==状态==" + lightState + "==>" + (lightState ? "开着的" : "关着的"));
        }
    }

    private synchronized void close() {
        if (lightState) {
            lightState = false;
            System.out.println(Thread.currentThread().getName() + "==状态==" + lightState + "==>" + (lightState ? "开着的" : "关着的"));
        }
    }

    // 类开灯

    class TurnOn implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                open();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    System.err.println("有虫子");
                }
            }

        }
    }

    class TurnOff implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                close();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    System.err.println("有虫子");
                }
            }
        }
    }

    // 类关灯

    // main 开  关

    public static void main(String[] args) {
        Lamp h = new Lamp();
        TurnOn turnOn = h.new TurnOn();

        TurnOff turnOff = h.new TurnOff();

        new Thread(turnOn, "开灯").start();
        new Thread(turnOff, "关灯").start();
    }
}
